package com.soft.mainsite.module.staticresource.service.impl;

import com.google.common.collect.Lists;
import com.soft.mainsite.common.exception.SystemException;
import com.soft.mainsite.module.staticresource.entity.StaticResourceFile;
import com.soft.mainsite.module.staticresource.service.StaticResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * StaticResourceServiceImpl此类用于静态资源展示
 *
 * @author: hujm
 * @date: 2019年09月03日 16:45
 * @remark:
 */
@Slf4j
@Service
public class StaticResourceServiceImpl implements StaticResourceService {

    @Value("${system.static.path}")
    private String destFilePath;

    private final String WIN = "win";

    private final String OSNAME = "os.name";

    @Override
    public List<StaticResourceFile> findAll() {
        ArrayList<StaticResourceFile> staticResourceFileList = Lists.newArrayList();
        File staticResourceFile = new File(getStaticResourcePath());
        log.info("读取静态资源文件路径： " + getStaticResourcePath());
        if (!staticResourceFile.exists() || staticResourceFile.listFiles().length < 1){
            throw new SystemException("请检查静态资源文件目录是否存在！");
        }

        // 只遍历三级目录
        for (File file : staticResourceFile.listFiles()) {
            // 第一层目录 big, icon, pc, xgwy, xgwy_m
            StaticResourceFile resourceFile = new StaticResourceFile();
            resourceFile.setFileName(file.getName());
            resourceFile.setFilePath(file.getAbsolutePath().replaceAll("\\\\", "/"));
            resourceFile.setIsDirectory(file.isDirectory());
            if (file.isDirectory()){
                File subFile = new File(file.getAbsolutePath());
                ArrayList<StaticResourceFile> childList = Lists.newArrayList();
                for (File secondaryFile : subFile.listFiles()) {
                    // 第二层级目录
                    StaticResourceFile subResourceFile = new StaticResourceFile();
                    subResourceFile.setFileName(secondaryFile.getName());
                    subResourceFile.setFilePath(secondaryFile.getAbsolutePath().replaceAll("\\\\", "/"));
                    subResourceFile.setIsDirectory(secondaryFile.isDirectory());
                    if (secondaryFile.isDirectory()){
                        ArrayList<StaticResourceFile> subChildList = Lists.newArrayList();
                        File subSecondaryFile = new File(secondaryFile.getAbsolutePath());
                        if (!subSecondaryFile.exists() || subSecondaryFile.listFiles().length < 1){
                            continue;
                        }
                        for (File subSecondary : subSecondaryFile.listFiles()) {
                            // 第三层
                            StaticResourceFile subChildStaticResourceFile = new StaticResourceFile();
                            subChildStaticResourceFile.setFileName(subSecondary.getName());
                            subChildStaticResourceFile.setFilePath(subSecondary.getAbsolutePath().replaceAll("\\\\", "/"));
                            subChildStaticResourceFile.setIsDirectory(subSecondary.isDirectory());
                            if (subSecondary.isDirectory()){
                                ArrayList<StaticResourceFile> thirdChildList = Lists.newArrayList();
                                File thirdChildFile = new File(subSecondary.getAbsolutePath());
                                if (!thirdChildFile.exists() || thirdChildFile.listFiles().length < 1){
                                    continue;
                                }
                                for (File listFile : thirdChildFile.listFiles()) {
                                    StaticResourceFile thirdChildStaticFile = new StaticResourceFile();
                                    thirdChildStaticFile.setFileName(listFile.getName());
                                    thirdChildStaticFile.setFilePath(listFile.getAbsolutePath().replaceAll("\\\\", "/"));
                                    thirdChildStaticFile.setIsDirectory(listFile.isDirectory());
                                    thirdChildList.add(thirdChildStaticFile);
                                }
                                subChildStaticResourceFile.setChildList(thirdChildList);
                            }
                            subChildList.add(subChildStaticResourceFile);
                        }
                        subResourceFile.setChildList(subChildList);
                    }
                    childList.add(subResourceFile);
                }
                resourceFile.setChildList(childList);
            }
            staticResourceFileList.add(resourceFile);
        }
        return staticResourceFileList;
    }

    @Override
    public StaticResourceFile findByPath(String path) {
        File file = new File(path);
        if (!file.exists()){
            throw new SystemException("静态资源不存在请检查！");
        }

        return setStaticResourceFile(file);
    }

    @Override
    public void upload(MultipartFile[] files, String currentPath) {

        ArrayList<String> fileTypeList = Lists.newArrayList();
        fileTypeList.add(".jpg");
        fileTypeList.add(".png");
        fileTypeList.add(".gif");
        fileTypeList.add(".css");
        fileTypeList.add(".js");
        fileTypeList.add(".mp4");

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            log.info("上传的文件名为：" + originalFilename);
            // 获取文件类型
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("上传的文件类型为：" + fileType);
            if (!fileTypeList.contains(fileType)){
                throw new SystemException("文件格式有误, 请重新上传!");
            }
            // 文件上传路径
            String staticResourcePath = getStaticResourcePath();
            log.info("文件上传的根目录：" + staticResourcePath);
            File dest = new File(staticResourcePath + currentPath + File.separator + originalFilename);
            if (!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                log.error("静态资源文件上传异常，{}", e.getMessage());
                e.printStackTrace();
            }
        }

    }

    @Override
    public void deleteByPath(String filePath) {
        File file = new File(filePath);
        if (!file.exists()){
            throw new SystemException("静态资源文件不存在，请查看！");
        }
        log.info("----------删除静态文件----------" + file);
        file.delete();
    }

    private StaticResourceFile setStaticResourceFile(File file){
        String parentPath = file.getParent();
        String[] split = null;
        if (System.getProperty(OSNAME).toLowerCase().startsWith(WIN)){
            split = parentPath.split("www");
        }else {
            String[] linuxStr = parentPath.split("wwwroot");
            split = linuxStr[1].split("www");
        }

        StaticResourceFile staticResourceFile = new StaticResourceFile();
        if (split.length > 1){
            staticResourceFile.setParentPath(split[1]);
        }else {
            staticResourceFile.setParentPath(File.separator);
        }
        staticResourceFile.setFileName(file.getName());
        staticResourceFile.setFilePath(file.getAbsolutePath());
        staticResourceFile.setIsDirectory(file.isDirectory());

        return staticResourceFile;
    }


    /**
     * 获取静态资源路径
     *
     * @return
     */
    private String getStaticResourcePath (){
        StringBuilder sb = new StringBuilder();
        sb.append(destFilePath);
        return sb.toString().replaceAll("\\\\", "/");
    }
}
